package org.springboot.szsrcb.controller;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springboot.szsrcb.entity.User;
import org.springboot.szsrcb.srvice.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;



@Controller
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

	@RequestMapping(value="/login",method={RequestMethod.GET})
	public String login(HttpServletRequest request,
			Model model) {
		logger.info("access login page.");
		
		model.addAttribute("user",new User());		
		return "login";
		//return "forward:/index";
	}
	
	@RequestMapping(value="/logout",method={RequestMethod.GET})
	public String logout(HttpServletRequest request,HttpSession session) {
		logger.info("access out page.");
		
		session.setAttribute("user", null);  
		session.setAttribute("login_name", null);
		return "login";
		//return "forward:/index";
	}
	
	@RequestMapping(value="/regrister",method={RequestMethod.GET})
	public String login(HttpServletRequest request) {
		logger.info("access regrister page.");
	//	logger.info("request.getMethod:"+request.getMethod());
			
		return "regrister";
		//return "forward:/index";
	}
	
	
	@RequestMapping(value="/change_pwd",method={RequestMethod.GET})
	public String change_pwd(HttpServletRequest request) {
		logger.info("access change_pwd page.");
	//	logger.info("request.getMethod:"+request.getMethod());
			
		return "change_pwd";
		//return "forward:/index";
	}
	/*
	@RequestMapping(value="/login",method={RequestMethod.POST})
	public String login(HttpServletRequest request,
			Model model,User user) {
		model.addAttribute("user",user);	
		logger.info("login user:"+user.getName());
		logger.info("pwd user:"+user.getPwd());
		logger.info("request.getMethod:"+request.getMethod());
		
		return "redirect:/index";		
		//return "index";
	}
	*/
	@RequestMapping("/")
	public String root(HttpSession httpSession, Model model) {
		String login_name=(String) httpSession.getAttribute("login_name"); 
		if(login_name!=null){
			User u = userService.search_a_user(login_name);
			boolean is_leader = userService.is_leader(u.getName());
			//model.addAttribute("is_leader", is_leader);
			model.addAttribute("user_role", u.getRole());
			model.addAttribute("user_name", u.getName());
			logger.info("access root page.");
			return "index";
		}else{
			logger.info("access login page.");
			return "login";
		}
		
	}

}
